package com.rt.easyjava.base.biz1.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rt.easyjava.base.biz1.bean.TmptDataOption;
import com.rt.easyjava.base.biz1.dto.TmptDataOptionDto;
import com.rt.easyjava.base.biz1.service.intf.TmptDataOptionService;
import com.rt.tmpt.service.utils.SpringContextHolder;
import com.rt.easyjava.common.base.MyQueryWrapper;
import com.rt.easyjava.common.base.Result;
import com.rt.easyjava.common.config.dozer.MyMapper;
import com.rt.easyjava.common.exception.ControllerException;
import com.rt.easyjava.common.utils.others.DateTool;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Method;

/**
 * 前端控制器
 * @author wuxiaoyong
 * @since 2020-05-01
 * 用户信息可直接形参获取：String (_userId，_loginName，_userName，_companyId，_userJson)
 */
@Api(tags = "TmptDataOptionController -  控制类")
@RequestMapping("/coding/tmptDataOption")
@Controller
public class TmptDataOptionController extends ControllerException {
    private final Logger logger = LoggerFactory.getLogger(TmptDataOptionController.class);

    @Autowired
    private MyMapper mapper;
    @Autowired
    private TmptDataOptionService tmptDataOptionService;


    @PreAuthorize("hasAuthority('tmptData:query')")
    @ApiOperation("分页查询列表（适合单表查询）")
    @GetMapping(value = "/page")
    @ResponseBody
    public Result page(@ModelAttribute TmptDataOptionDto tmptDataOptionDto){
        Result<TmptDataOptionDto> result = new Result<>();

        Page<TmptDataOption> page = new Page<>(tmptDataOptionDto.getPage(), tmptDataOptionDto.getLimit());

        TmptDataOption tmptDataOption = mapper.map(tmptDataOptionDto, TmptDataOption.class);
        if(tmptDataOption.getDeleteflag()==null){
            tmptDataOption.setDeleteflag(0);
        }

        QueryWrapper<TmptDataOption> queryWrapper=new QueryWrapper<>(tmptDataOption);
        //特殊查询条件
        queryWrapper.gt(tmptDataOptionDto.getCreatedate_Start()!=null,"createdate",tmptDataOptionDto.getCreatedate_Start());
        queryWrapper.lt(tmptDataOptionDto.getCreatedate_End()!=null,"createdate",tmptDataOptionDto.getCreatedate_End());
        tmptDataOption.setCreateman(null);
        queryWrapper.like(tmptDataOptionDto.getCreateman()!=null,"createman",tmptDataOptionDto.getCreateman());
        queryWrapper.orderBy(tmptDataOptionDto.getCondition(), tmptDataOptionDto.isAsc(), tmptDataOptionDto.getColumn());

        return tmptDataOptionService.page(page, queryWrapper);
    }



    @PreAuthorize("hasAuthority('tmptData:query')")
    @ApiOperation("自定义sql分页查询（mapper.xml, 适合多表查询）")
    @GetMapping(value = "/myPage")
    @ResponseBody
    public Result myPage(@ModelAttribute TmptDataOptionDto tmptDataOptionDto){
        Result<TmptDataOptionDto> result = new Result<>();

        Page<TmptDataOption> page = new Page<>(tmptDataOptionDto.getPage(), tmptDataOptionDto.getLimit());

        TmptDataOption tmptDataOption = mapper.map(tmptDataOptionDto, TmptDataOption.class);
        if(tmptDataOption.getDeleteflag()==null){
            tmptDataOption.setDeleteflag(0);
        }

        // 多表查询时，plus自带不支持，这里封装一个工具类处理，mapper.xml中主表别名是t1, 给所有非空字段加别名； 特殊查询条件，在工具类中要忽略掉，最后自定义增加。
        QueryWrapper<TmptDataOption> queryWrapper = MyQueryWrapper.buildQueryWrapper(tmptDataOption , "createdate", "createman");
        //特殊查询条件
        queryWrapper.gt(tmptDataOptionDto.getCreatedate_Start()!=null,"t1.createdate",tmptDataOptionDto.getCreatedate_Start());
        queryWrapper.lt(tmptDataOptionDto.getCreatedate_End()!=null,"t1.createdate",tmptDataOptionDto.getCreatedate_End());
        queryWrapper.like(tmptDataOptionDto.getCreateman()!=null,"t1.createman",tmptDataOptionDto.getCreateman());
        // queryWrapper.orderBy(tmptDataOptionDto.getCondition(), tmptDataOptionDto.isAsc(), tmptDataOptionDto.getColumn());
        queryWrapper.orderBy(true, true, "sort");

        result = tmptDataOptionService.myPage(page, queryWrapper);

        return result;
    }


    @PreAuthorize("hasAuthority('tmptData:query')")
    @ApiOperation("查询所有")
    @GetMapping(value = "/selectAll")
    @ResponseBody
    public Result selectAll(@ModelAttribute TmptDataOptionDto tmptDataOptionDto){
        Result<TmptDataOptionDto> result = new Result<>();


        TmptDataOption tmptDataOption = mapper.map(tmptDataOptionDto, TmptDataOption.class);
        if(tmptDataOption.getDeleteflag()==null){
            tmptDataOption.setDeleteflag(0);
        }

        QueryWrapper<TmptDataOption> queryWrapper=new QueryWrapper<>(tmptDataOption);
        //特殊查询条件
        queryWrapper.gt(tmptDataOptionDto.getCreatedate_Start()!=null,"createdate",tmptDataOptionDto.getCreatedate_Start());
        queryWrapper.lt(tmptDataOptionDto.getCreatedate_End()!=null,"createdate",tmptDataOptionDto.getCreatedate_End());
        tmptDataOption.setCreateman(null);
        queryWrapper.like(tmptDataOptionDto.getCreateman()!=null,"createman",tmptDataOptionDto.getCreateman());
        queryWrapper.orderBy(tmptDataOptionDto.getCondition(), tmptDataOptionDto.isAsc(), tmptDataOptionDto.getColumn());

        result = tmptDataOptionService.selectAll(queryWrapper);

        return result;
    }


    @PreAuthorize("hasAuthority('tmptData:query')")
    @ApiOperation("selectById")
    @GetMapping(value = "/selectById")
    @ResponseBody
    public Result selectById(Long id){
        //调用服务
        return tmptDataOptionService.selectById(id);
    }


    @PreAuthorize("hasAuthority('tmptData:query')")
    @ApiOperation("SQL动态多选项, spring动态调用")
    @GetMapping(value = "/select4column")
    @ResponseBody
    public Result select4column(String columnName){
        try{
            Object o = SpringContextHolder.getBean("tmptDataOptionService");
            Method method = o.getClass().getMethod("mySelect4"+columnName);
            return Result.builder(method.invoke(o)).success();
        }catch (Exception e){
            e.printStackTrace();
            return Result.builder().fault(columnName+"多选项取值失败");
        }
    }

    @PreAuthorize("hasAuthority('tmptData:create')")
    @ApiOperation("新增对象")
    @PostMapping(value = "/create")
    @ResponseBody
    public Result create(@RequestBody TmptDataOptionDto tmptDataOptionDto,
                    String _userId, String _userName, String _companyId){
        //插入参数
        tmptDataOptionDto.setCreatemanId(Long.parseLong(_userId));
        tmptDataOptionDto.setCreateman(_userName);
        tmptDataOptionDto.setCreatedate(DateTool.getCurrentDatetimeStr());
        tmptDataOptionDto.setCompanyId(Long.parseLong(_companyId));

        //调用服务
        return tmptDataOptionService.create(tmptDataOptionDto);
    }


    @PreAuthorize("hasAuthority('tmptData:update')")
    @ApiOperation("编辑对象")
    @PostMapping(value = "/update")
    @ResponseBody
    public Result update(@RequestBody TmptDataOptionDto tmptDataOptionDto,
                        String _userId, String _userName){
        //参数
        tmptDataOptionDto.setModifymanId(Long.parseLong(_userId));
        tmptDataOptionDto.setModifyman(_userName);
        tmptDataOptionDto.setModifydate(DateTool.getCurrentDatetimeStr());
        tmptDataOptionDto.setCreatedate(null);
        tmptDataOptionDto.setCreateman(null);
        tmptDataOptionDto.setCreatemanId(null);
        tmptDataOptionDto.setCompanyId(null);

        //query condition for update
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id", tmptDataOptionDto.getId()==null?"0":tmptDataOptionDto.getId().longValue());

        //调用服务
        return tmptDataOptionService.update(tmptDataOptionDto, updateWrapper);
    }


    @PreAuthorize("hasAuthority('tmptData:delete')")
    @ApiOperation("逻辑删除对象，由deleteflag控制：0:有效，1:已删除。")
    @PostMapping(value = "/delete")
    @ResponseBody
    public Result delete(Long id, String _userId, String _userName){
        Result result = new Result();

        //参数
        TmptDataOptionDto tmptDataOptionDto = new TmptDataOptionDto();
        tmptDataOptionDto.setModifymanId(Long.parseLong(_userId));
        tmptDataOptionDto.setModifyman(_userName);
        tmptDataOptionDto.setModifydate(DateTool.getCurrentDatetimeStr());
        tmptDataOptionDto.setDeleteflag("1");

        //query condition for update
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id", id==null?0:id.longValue());

        //调用服务
        return tmptDataOptionService.update(tmptDataOptionDto, updateWrapper);
    }


    @PreAuthorize("hasAuthority('tmptData:deletePhysical')")
    @ApiOperation("物理删除对象，默认注释了核心调用方法，请按需启用")
    @PostMapping(value = "/deletePhysical")
    @ResponseBody
    public Result deletePhysical(Long id){
        Result result = new Result();

        //调用服务
        Boolean aBoolean =  false;//tmptDataOptionService.removeById(id==null?0:id.longValue());
        if(aBoolean){
            result.success();
        }else {
            result.fault();
        }

        return result;
    }

}
